package com.woodws.core.resolver;

import com.slyak.spring.jpa.PageParams;
import com.woodws.core.data.PageParamsImpl;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import java.util.Iterator;

public class PageParamsResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.getParameterType() == PageParams.class;
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter,
                                  ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest,
                                  WebDataBinderFactory webDataBinderFactory) throws Exception {


        String page = nativeWebRequest.getParameter("page");
        PageParams pageParams;
        if(page != null && page.equals("")){
            String size = nativeWebRequest.getParameter("size");
            pageParams = new PageParamsImpl(Integer.parseInt(page),Integer.parseInt(size));
        }else{
            pageParams = new PageParamsImpl();
        }

        Iterator<String> names = nativeWebRequest.getParameterNames();
        while (names.hasNext()){
            String name = names.next();
            String value = nativeWebRequest.getParameter(name);
            pageParams.set(name,value);
        }
        return pageParams;
    }
}
